package com.romotc.qqrobot.bean;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.romotc.oschina.db.QueryHelper;
import com.romotc.qqrobot.webqq.bean.Send_buddy_msg2_RequestBody;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Send_buddy_msg2_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.DateProcessor;
import com.romotc.scache.RequestSpy;

public class SendMsgService {
	private static SendMsg dbInstance = new SendMsg();
	
	public static SendMsg save2Db(Send_buddy_msg2_RequestBody msg) {
		if(msg == null)
			return null;
		
		SendMsg dbMsg = new SendMsg(msg);
		dbMsg.Save();
		return dbMsg;
	}

	/**
	 * 查询入参QQ对象的待发消息
	 * @param curQq
	 * @return 最多5条
	 */
	private int pageSize = 5;
	public static List<SendMsg> qryMySendTask(QQLogedin curQq) {
		String filter = "senderQQ = " + curQq.getUin() + " and status = 0";
		return (List<SendMsg>)dbInstance.FilterOrderBy(filter, "id ASC", 1, 5);
	}
	
	
	/**
	 * 发送消息并修改已发送消息的状态
	 * @param sendList
	 */
	public static void sendMsg(List<SendMsg> sendList) {
		if(sendList == null || sendList.isEmpty()) {
			return;
		}
		
		for(SendMsg sendMsg : sendList) {
			try {
				sendMsg(sendMsg);
			} catch (Exception e) {
				modifySendMsgNote(sendMsg, "error in sendMsg:" + e.getMessage());
				modifySendMsgStatus(sendMsg, SendMsg.Key_Status_Sended);
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 发送消息并修改已发送消息的状态
	 * @param sendMsg
	 * @throws Exception 
	 */
	public static void sendMsg(SendMsg sendMsg) throws Exception {
		if(sendMsg == null)
			return;
		
		if(sendMsg.getId() == 0) {
			sendMsg.Save();
		}
		
		QQLogedin senderQQ = QQLogedin.getCurQqLogedIn(String.valueOf(sendMsg.getSenderQQ()));
		if(senderQQ == null || !senderQQ.active) {
			modifySendMsgNote(sendMsg, "senderQQ is null or is not active");
			return;
		}
		
		//客户对应的UIN
		QQUserFriend quf = null;
		try {
			quf = QQUserFriendService.qryQFriendByCustId(senderQQ, -sendMsg.getSendTo());
		} catch (Exception e) {
			modifySendMsgNote(sendMsg, "error in qryQFriendByCustId:" + e.getMessage());
			return;
		}
		if(quf == null)
		{
			modifySendMsgNote(sendMsg, "cant't find QQUserFriend by sendTo id");
			return;
		}
		
		//接收者uin
		long reciverUin = quf.getUin();
		
		//开始调接口发送
		JSONObject reqDataObj = new JSONObject();
		Send_buddy_msg2_InterCall sendMsgCall = Send_buddy_msg2_InterCall.getInstance();
		
		String msg = sendMsg.getMsgContext_data();
//		msg = msg.replace("\\n", "");
		//dddd","【提示：此用户正在使用Q+ Web：http://web.qq.com/】
		msg = msg.replace("\",\"\\n【提示：此用户正在使用Q+ Web：http://web.qq.com/】", "");
		msg = msg.replace("\\n", "\\\\n");
		reqDataObj.put(Send_buddy_msg2_InterCall.Key_MsgStr, msg);
		reqDataObj.put(Send_buddy_msg2_InterCall.Key_Send2Uin, reciverUin);
		reqDataObj.put("Key_sendMsgObj", sendMsg);
		
		//调用发送消息接口发送消息
		sendMsgCall.call(senderQQ, reqDataObj, 
				new DateProcessor(){//根据接口调用情况修改数据库记录

			@Override
			public JSONObject processResponse(QQLogedin loginQQ,
					RequestSpy rqSpy, JSONObject reqDataObj) throws Exception {
				String resBody = rqSpy.getResBody();
				if(StringUtils.isNotBlank(resBody)) {
					SendMsg sendMsg = (SendMsg)reqDataObj.get("Key_sendMsgObj");
					if(resBody.indexOf("result\":\"ok\"}") != -1) {
						//发送成功
						modifySendMsgStatus(sendMsg, SendMsg.Key_Status_Sended);
					}else {
						if(resBody.length() > 90)
							resBody = resBody.substring(0, 90);
						
						modifySendMsgNote(sendMsg, resBody);
						modifySendMsgStatus(sendMsg, SendMsg.Key_Status_Sended);
					}
				}
				reqDataObj.remove("Key_sendMsgObj");
				return reqDataObj;
			}
			
		});
		
		//休眠一秒
		Thread.sleep(2000);
	}


	/**
	 * 修改状态
	 * @param sendMsg
	 * @param status
	 */
	public static void modifySendMsgStatus(SendMsg sendMsg,
			int status) {
		if(sendMsg == null)
			return;
		
		String sql = "UPDATE " + sendMsg.TableName() + " SET status = ? WHERE id = ?";
		QueryHelper.update(sql, status, sendMsg.getId());
	}


	/**
	 * 
	 * @param sendMsg
	 * @param string
	 */
	public static void modifySendMsgNote(SendMsg sendMsg, String note) {
//		boolean dr = Evict(QueryHelper.update("DELETE FROM " + TableName() + " WHERE id=?", getId()) == 1);
		//UPDATE `osc_send_msgs` SET `note`='DDD' WHERE (`id`='1')
		if(sendMsg == null || note == null)
			return;
		if(note.length() > 255)
			note = note.substring(0, 255);
		
		String sql = "UPDATE " + dbInstance.TableName() + " SET note = ? WHERE id = ?";
		QueryHelper.update(sql, note, sendMsg.getId());
	}
	
	
	public static void main(String[] args) {
		SendMsg sendMsg = new SendMsg();
		sendMsg.setId(1);
//		modifySendMsgNote(sendMsg, "ddddddddddddddddddd");
		modifySendMsgStatus(sendMsg, 1);
	}
	

}
